#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <string>
#include <iostream>
#include <stdexcept>
#include <cstring>
#include <sstream>
void ShowHelpMsg()
{
  std::cout<<"The CameraClient Test Help"<<std::endl
    <<"0: Exit"<<std::endl
    <<"1: Start Monitor"<<std::endl
    <<"2: Stop Monitor"<<std::endl
    <<"3: Start Record"<<std::endl
    <<"4: Stop Record"<<std::endl
    <<"5: Record Status"<<std::endl
    <<"6: Monitor Status"<<std::endl
    <<"Please input you command: "
    ;
}

char* sendBuffer;
long sendBufferSize;

void SendMsg(mqd_t id,const std::string & data)
{
  if(mq_send(id,data.c_str(),data.size(),0)==-1)
    std::cerr<<"无法发送POSIX消息"<<std::endl;
}

std::string ReceiveMsg(mqd_t id)
{
  std::size_t size=mq_receive(id,sendBuffer,sendBufferSize,nullptr);
  return std::string(sendBuffer,size);
}

int main()
{
  mqd_t msgQueue=mq_open("/HBTY_MSGSERVER_CAMERACOLLEGE",O_EXCL | O_RDWR);
  if(msgQueue==-1)
    throw std::runtime_error("无法打开消息队列");
  struct mq_attr attr;
  mq_getattr(msgQueue,&attr);
  sendBufferSize=attr.mq_msgsize;
  sendBuffer=new char[attr.mq_msgsize];

  int inputVal;
  while(true)
  {
    ShowHelpMsg();
    std::cin>>inputVal;
    switch(inputVal)
    {
      case 0:
        return 0;

      case 1:
        SendMsg(msgQueue,"Monitor Start");
      break;
      case 2:
        SendMsg(msgQueue,"Monitor Stop");
      break;
      case 3:
        {
        std::string path;
        std::cout<<"Input Save Path : ";
        std::cin>>path;
        SendMsg(msgQueue,[&path]()->std::string{
            std::stringstream ss;
            ss<<"Record Start "<<path;
            return ss.str();
          }().c_str());
        }
      break;
      case 4:
        SendMsg(msgQueue,"Record Stop");
      break;
      case 5:
        SendMsg(msgQueue,"Status Record");
        std::cout<<ReceiveMsg(msgQueue)<<std::endl;
      break;
      case 6:
        SendMsg(msgQueue,"Status Monitor");
        std::cout<<ReceiveMsg(msgQueue)<<std::endl;
      break;
      default:
        std::cout<<"Can't understand your input number"<<std::endl;
    }
  }

  delete [] sendBuffer;
}
